import { Actions, PortalApis } from '../../core/utils/IConstant';
import Config from '../../core/utils/Config';
import HttpClient from '../../core/utils/HttpClient';
import WebDB from '../../core/utils/WebDB';

export function setScrollerPositionAction(offset, playOffset)
{
    return {
        type: Actions.HOME.SET_SCROLL_OFFSET,
        scrollViewOffset: offset,
        playScrollViewOffset: playOffset,
    };
}

export function asyncGetHomeNewsListAction()
{
    return function(dispatch, getState)
    {
        let state = getState();
        dispatch(_getNewsListRequestAction());
        return _fetchNewsList().then((resp)=>{
            dispatch(_getNewsListSuccessAction(resp ? resp.results : []));
        }).catch((error)=>{
            dispatch(_getNewsListFailureAction(error));
        });
    };
}

export function increaseNewsClickCount(code)
{
    return {
        type: Actions.HOME.NEWS_INCREASE_CLICK_COUNT,
        code,
    };
}

function _fetchNewsList()
{
    let kvDict = {
        Identifier: 'know/dynamic/news',
        pageIndex: 1,
        pageSize: 2
    };
    return HttpClient.getFromPortal(PortalApis.NEWS.LIST, kvDict)
        .then((resp) => resp.json());
}

function _getNewsListRequestAction()
{
    return {
        type: Actions.HOME.GET_NEWS_REQUEST
    };
}

function _getNewsListSuccessAction(newsList)
{
    return {
        type: Actions.HOME.GET_NEWS_SUCCESS,
        dataList: newsList
    };
}

function _getNewsListFailureAction(error)
{
    return {
        type: Actions.HOME.GET_NEWS_FAILURE,
        message: error
    };
}

export function asyncGetHomeWeatherAction(isServer)
{
    return function(dispatch, getState)
    {
        return _fetchWeather(isServer).then((resp)=>{
            WebDB.setItem('HOME_WEATHER', resp);
            resp = resp.results && resp.results.length > 0  ? resp.results[0] : null;
            dispatch(_getWeatherSuccessAction(resp));
        }).catch((error)=>{
            console.log(`error: ${error}`);
        });
    };
}

function _fetchWeather(isServer)
{
    let now=new Date().getTime();
    let oldTime = WebDB.getItem('HOME_WEATHER_TIME') ? parseInt(WebDB.getItem('HOME_WEATHER_TIME'), 10) : 0;
    if (now - oldTime <= 8 * 60 * 60 * 1000 && WebDB.getItem('HOME_WEATHER') && WebDB.getItem('HOME_WEATHER').length > 0) {
        let resp = JSON.parse(WebDB.getItem('HOME_WEATHER'));
        return new Promise((resolve) => {
            resolve(resp);
        });
    }
    let url = HttpClient.HOST_WEATHER;
    let kvDict = {
        location: Config.instance.weatherCityName,
        output: 'json',
        ak: 'wzkXpn7CyH8zOpOfFzUYaXnr96M6pq3e'
    };
    WebDB.setItem('HOME_WEATHER_TIME', new Date().getTime());
    return isServer ? HttpClient.getData(url, kvDict).then((resp) => resp.json()) : HttpClient.getDataWithJsonp(url, kvDict);
}

function _getWeatherSuccessAction(resp)
{
    return {
        type: Actions.HOME.GET_WEATHER_SUCCESS,
        resp
    };
}